#pragma once
#include "log.hpp"
#include <arpa/inet.h>
#include <cerrno>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include<iostream>
#include <netinet/in.h>
#include <string>
#include <sys/socket.h>
#include <unistd.h>
#include <unordered_map>

class UdpServer
{
public:
    UdpServer(uint16_t port,std::string ip="")
    :_port(port),_ip(ip)
    ,_sock(-1)
    {
        
    }
    bool initServer()
    {
        _sock=socket(AF_INET,SOCK_DGRAM,0);
        if(_sock < 0)
        {
            logMessage(FATAL,"%d:%s",errno,strerror(errno));
            exit(1);
        }
        struct sockaddr_in server;
        bzero(&server,sizeof(server));
        server.sin_family=AF_INET;
        server.sin_port=htons(_port);
        server.sin_addr.s_addr=inet_addr(_ip.c_str());
        if(bind(_sock,(struct sockaddr*)&server,sizeof(server)) < 0)
        {
            logMessage(FATAL,"%d:%s",errno,strerror(errno));
            exit(2);
        }
    }
    void start()
    {
        char buffer[1024];
        while(true)
        {
            struct sockaddr_in client;
            bzero(&client,sizeof(client));
            socklen_t len=sizeof(client);
            char key[64];
            ssize_t s=recvfrom(_sock,buffer,sizeof(buffer)-1,0,
            (struct sockaddr*)&client,&len);
            if(s > 0)
            {
                std::string client_ip=inet_ntoa(client.sin_addr);
                uint16_t client_port=ntohs(client.sin_port);
                snprintf(key,sizeof(key),"%s-%u",client_ip.c_str(),client_port);
                auto it=_users.find(key);
                if(it==_users.end()){
                    _users.insert({key,client});
                }
            }
            for(auto& iter:_users)
            {
                std::string message=key;
                message+="#";
                message+=buffer;
                sendto(_sock,message.c_str(),message.size(),0,
                (struct sockaddr*)&client,len);
            }
        }
    }
    ~UdpServer(){
        if(_sock >= 0){
            close(_sock);
        }
    }
private:
    uint16_t _port;
    std::string _ip;
    int _sock;
    std::unordered_map<std::string, struct sockaddr_in> _users;
};
